import 'package:flutter/material.dart';
import 'package:lib_module_manager/component_manager/component_delegate.dart';
import 'package:lib_module_manager/module_manager/page.dart' as module_manager;
import 'package:rxdart/subjects.dart';

typedef CreateComponent = Component? Function({
  required module_manager.Page page,
  required String id,
  dynamic value,
});

abstract class Component {
  final Key _pageKey = const ValueKey("page");
  final Expando<module_manager.Page> _page = Expando("page");
  module_manager.Page get page => _page[_pageKey]!;

  String type;
  String id;

  BehaviorSubject<dynamic> valueObservable;

  dynamic get value => valueObservable.value;
  set value(dynamic data) => valueObservable.add(data);

  late Widget widget;

  final Key _delegateKey = const ValueKey("delegate");
  final Expando<ComponentDelegate> _delegate = Expando("delegate");
  ComponentDelegate? get delegate => _delegate[_delegateKey];
  set delegate(ComponentDelegate? value) => _delegate[_delegateKey] = value;

  Component(
      {required module_manager.Page page, required this.type, required this.id, dynamic value})
      : valueObservable = BehaviorSubject.seeded(value) {
    _page[_pageKey] = page;
  }

  Future<dynamic> callMethod({required String method, dynamic param}) async {}

  void postMessage({required String message, dynamic param}) {
    delegate?.onMessage(this, message: message, param: param);
  }
}
